package socket;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;

public class Server {

    public static void main(String[] args) throws IOException {
        ServerSocket serverSocket = new ServerSocket(8051);

        for (; ; ) {
            Socket socket = serverSocket.accept();//侦听该套接字连接
            ServerThread thread = new ServerThread(socket);
            thread.run();
        }

    }

    private static class ServerThread implements Runnable {
        private final Socket socket;

        public ServerThread(Socket socket) {
            this.socket = socket;
        }

        @Override
        public void run() {
            try (InputStream is = socket.getInputStream();
                 InputStreamReader reader = new InputStreamReader(is);
                 BufferedReader buffer = new BufferedReader(reader);) {

                String temp;
                String info = "";
                while ((temp = buffer.readLine()) != null) {
                    info += temp;
                    System.out.println("收到客户端信息:" + info + ", 当前客户端ip:" + socket.getInetAddress().getHostAddress());
                }

                OutputStream os = socket.getOutputStream();
                PrintWriter writer = new PrintWriter(os);
                writer.print("您好，服务端已接收消息");
                writer.flush();
                socket.shutdownOutput();

                writer.close();
                os.close();
                buffer.close();
                reader.close();
                is.close();
                socket.close();
            } catch (Exception e) {

            }
        }
    }
}
